package de.se.ludoapp.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import de.se.ludoapp.LudoApplication;
import de.se.ludoapp.R;
import de.se.ludoapp.activity.task.OpenGamesTask;
import de.se.ludoapp.activity.task.SendRequestTask;
import de.se.ludoapp.gaming.Game;

/**
 * Shows a list of all open games, wich are not started. Function to open a new
 * game.
 * 
 * @author Marlen Rotert
 * 
 */
public class PlayerTableActivity extends Activity {

	private LudoApplication ludoApp;

	private Handler handler;

	private Runnable runnable;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Initialise Stub LudoServer
		ludoApp = (LudoApplication) this.getApplication();

		// View
		setContentView(R.layout.player_table);

		// button for opening new table
		Button buttonOpenNewGameTable = (Button) this
				.findViewById(R.id.buttonOpenNewGameTable);

		buttonOpenNewGameTable.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// open a new game table
				handler.removeCallbacks(runnable);
				Intent intentOpenNewGame = new Intent(PlayerTableActivity.this,
						NewGameActivity.class);
				intentOpenNewGame.putExtra("OpenNewGame", true);
				startActivity(intentOpenNewGame);
				finish();
			}

		});

		// ListView of open games
		final ListView listViewOpenGames = (ListView) this
				.findViewById(R.id.listViewOpenGames);
		listViewOpenGames.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// Game for send request
				Game gameForRequest = (Game) listViewOpenGames.getAdapter()
						.getItem(position);
				new SendRequestTask(ludoApp, PlayerTableActivity.this,
						gameForRequest).execute();
			}
		});

		// get all open games delay 1 sek
		handler = new Handler();
		runnable = new Runnable() {
			public void run() {
				new OpenGamesTask(ludoApp, PlayerTableActivity.this).execute();
				handler.postDelayed(this, 1000);
			}
		};
		handler.postDelayed(runnable, 100);
	}

	@Override
	protected void onPause() {
		super.onPause();
		handler.removeCallbacks(runnable);
	}

}
